package com.bysc.joinservice.service.impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bysc.baseservice.config.RabbitmqConfig;
import com.bysc.baseservice.handler.BaiYunException;
import com.bysc.commonutils.ResultCode;
import com.bysc.commonutils.Results;
import com.bysc.commonutils.utils.MD5;
import com.bysc.joinservice.controller.JoinActivityController;
import com.bysc.joinservice.entity.JoinActivity;
import com.bysc.joinservice.entity.JoinActivityForm;
import com.bysc.joinservice.mapper.JoinActivityMapper;
import com.bysc.joinservice.service.JoinActivityService;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * 报名表 服务实现类
 * </p>
 *
 * @author kkk
 * @since 2024-11-03
 */
@Service
public class JoinActivityServiceImpl extends ServiceImpl<JoinActivityMapper, JoinActivity> implements JoinActivityService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private JoinActivityMapper joinActivityMapper;


    /**
     * 检查用户与活动之间的状态[已提交/排队中/]
     *
     * @param id 活动id
     * @return 返回结果
     */
    @Override
    public Results checkActivityStatus(String id, String userId) {
        if (redisTemplate.opsForSet().isMember("activity:submit:" + id, userId)) {
            return Results.ok().data("status", 4).message("已提交报名表");
        } else if (redisTemplate.opsForSet().isMember("activity:join:" + id, userId)) {
            return Results.ok().data("status", 2).message("已抢到报名资格，请尽快提交报名表，15分钟后失效");
        } else if (redisTemplate.opsForSet().isMember("activity:queue:" + id, userId)) {
            return Results.ok().data("status", 3).message("排队中");
        } else if ("0".equals(JoinActivityController.status.get(id))) {
            return Results.ok().data("status", 0).message("名额已满");
        } else if (JoinActivityController.status.get(id) == null) {
            return Results.ok().data("status", 1).message("非法请求");
        }
        return Results.ok().data("status", 5).message("未报名");
    }


    @Override
    public void getNumber(String str, String id, String userId) {
        //.判断活动、报名状态
        Results results = checkActivityStatus(id, userId);
        if (results != null && (int) results.getData().get("status") == 5) {
            //2.判断密文
            String encrypt = MD5.encrypt(id + userId);
            if (!encrypt.equals(str)) {
                throw new BaiYunException(ResultCode.ERROR, "非法请求");
            }
            //3.redis hash 排队
            redisTemplate.opsForSet().add("activity:queue:" + id, userId);
            //4.MQ
            rabbitTemplate.convertAndSend(RabbitmqConfig.EXCHANGE_TOPICS_ACTIVITY, RabbitmqConfig.ROUTINGKEY_ACTIVITY_QUEUE, id + ":" + userId);
        } else {
            throw new BaiYunException(ResultCode.ERROR, results.getMessage());
        }
    }


    /**
     * 导出报名表
     *
     * @param response
     * @param id
     */
    @Override
    public void exportData(HttpServletResponse response, String id) {
        List<JoinActivityForm> list = joinActivityMapper.exportData(id);
        try {
            // 编码文件名
            String fileName = URLEncoder.encode(list.get(0).getSubject() + "报名表", "UTF-8").replaceAll("\\+", "%20");
            // 设置响应头
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            // 获取输出流
            ServletOutputStream outputStream = response.getOutputStream();
            // 写入Excel文件
            EasyExcel.write(outputStream, JoinActivityForm.class).sheet("表1").doWrite(list);
            // 刷新输出流
            outputStream.flush();
            // 关闭输出流
            outputStream.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
